package com.zbl.zblproject.core.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/22
 */
public class StringUtil {

    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左补0
                // sb.append(str).append("0");//右补0
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }


    public static String getFileSuffix(String name){
        if(isNullOrEmpty(name)){
            throw new NullPointerException("null string");
        }
        return name.substring(name.lastIndexOf('.') + 1, name.length());
    }


    public static String getFirstSpell(String chinese) {

        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
    }


    /**
     * 防sql注入
     * @param sql
     * @return
     */
    public static String sql(String sql){
        sql = sql.replaceAll("\'", "");
        sql = sql.replaceAll("%", "");
        return sql;
    }

    public static String save2Value(String value){
        String str = value.toString();
        if(str.endsWith(".0")) {
            str = str.substring(0, str.length()-2);
        } else if(str.endsWith(".00")) {
            str = str.substring(0, str.length()-3);
        } else {
            str = value.toString();
        }
        return str;
    }


    public static boolean isNullOrEmpty(String value){
        return value == null || value.trim().equals("");
    }
}
